package com.maistars.spider.security.realm;

import com.maistars.spider.repository.security.model.PermissionPO;
import com.maistars.spider.repository.security.model.RolePO;
import com.maistars.spider.repository.security.model.UserPO;
import com.maistars.spider.security.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

public class UserRealm extends JdbcRealm {

	@Autowired
	private UserService userService;
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// TODO Auto-generated method stub
		
		if (principals == null) {
            throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
        }
		//SimpleAuthorizationInfo
		//SimpleCookie
 		String username = (String) principals.getPrimaryPrincipal();
		UserPO user = userService.getUserDetailByUsername(username);
		RolePO role = new RolePO();
		PermissionPO permission = new PermissionPO();
		//角色名的集合 
		Set<String> roleSet = new HashSet<>();
		//权限名的集合 
		List<PermissionPO> permissionList = new ArrayList<>();
		
		Set<String> piSet = new HashSet<>();
		Iterator<?> iterator = user.getRoles().iterator();
		while(iterator.hasNext()) {
			role = (RolePO) iterator.next();
			roleSet.add(role.getRoleName());
			permissionList = role.getPermissions();
			//System.out.println(role.getPermissionSet());
		}
		
		iterator = permissionList.iterator();
		while (iterator.hasNext()) {
			permission = (PermissionPO) iterator.next();
			piSet.add(permission.getPermissionName());
		}
		
		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
		simpleAuthorizationInfo.addRoles(roleSet);
		simpleAuthorizationInfo.addStringPermissions(piSet);
		//simpleAuthorizationInfo.setStringPermissions(piSet);
		//simpleAuthorizationInfo =(SimpleAuthorizationInfo) super.doGetAuthorizationInfo(principals);
		return simpleAuthorizationInfo;
	}
	

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		AuthenticationInfo authenticationInfo = null;
		String username = (String) token.getPrincipal();
		UserPO user = userService.getUserByUsername(username);
		if (1 == user.getLocked()) {
			throw new LockedAccountException("账号被锁");
		}
		if (user.getStatus().equals(1)) {
			throw new DisabledAccountException();
		}
		if (user.getStatus().equals(2)) {
			throw new ExpiredCredentialsException();
		}		

		authenticationInfo = super.doGetAuthenticationInfo(token);
		return authenticationInfo;
	}


}
